<?php

declare(strict_types=1);

namespace app\controller\sys;

use think\facade\View;

use app\utils\ReUtils;
use app\model\SysMenu as SysMenuModel;

/**
 * 菜单控制器
 */
class SysMenu extends Base
{
    protected $modelName = "SysMenu";

    public function index()
    {
        $list = SysMenuModel::select();

        View::assign('list', list_tree($list, 'menuid'));

        View::assign('type',  ['目录', '菜单', '按钮']);
        View::assign('type_label',  ['primary', 'success', 'default']);

        return View::fetch();
    }

    public function save($id = 0)
    {
        if ($this->app->request->isPost()) {
            $param = $this->app->request->param();
            
            if ($param['name'] == '') {
                $this->error("目录名不能为空");
            }

            try {
                if ($param['id'] != 0) {
                    SysMenuModel::update([
                        'pid' => $param['pid'],
                        'name' => $param['name'],
                        'url' => $param['url'] ?: null,
                        'type' => $param['type'],
                        'icon' => $param['icon']
                    ], ['menuid'=>$param['id']]);
                } else {
                    SysMenuModel::create([
                        'pid' => $param['pid'],
                        'name' => $param['name'],
                        'url' => $param['url'] ?: null,
                        'type' => $param['type'],
                        'icon' => $param['icon']
                    ]);
                }
                // 删除菜单目录缓存
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }
            $this->success('操作成功', 'sys_menu/index');
        } else {
            if ($id != 0) {
                $data = SysMenuModel::find($id);
            } else {
                $data = new SysMenuModel();
            }
            
            View::assign('data', $data);

            return View::fetch();
        }
    }

    public function delete($id = null)
    {
        if ($this->app->request->isAjax()) {
            if (SysMenuModel::where('pid', $id)->value('menuid')) {
                return ReUtils::error('此权限子权限不为空, 若要删除请先清空子权限');
            }

            if ($id < 31) {
                return ReUtils::error('系统菜单不可删除');
            }

            if (SysMenuModel::destroy($id)) {
                return ReUtils::success();
            } else {
                return ReUtils::error();
            }
        }
    }
}
